package com.hafiery.sdk.bluetooth.transport.res;

import com.hafiery.sdk.bluetooth.util.HexUtil;
import com.hafiery.sdk.bluetooth.util.LogUtil;

import java.util.Arrays;
import static com.hafiery.sdk.bluetooth.transport.constant.OpCode.HEAD;
import static com.hafiery.sdk.bluetooth.transport.constant.OpCode.FLAG;
import static com.hafiery.sdk.bluetooth.transport.constant.OpCode.RESERVED;
import static com.hafiery.sdk.bluetooth.transport.constant.OpCode.TAIL;
public class ResponseData {

    private int opCode;
    private int errorCode;
    private byte[] data=new byte[]{};
    private boolean done;
    private ResponseData(int opCode, int errorCode, byte[] data,boolean done) {
        this.opCode = opCode;
        this.errorCode = errorCode;
        this.data = data;
        this.done = done;
    }

    public int getOpCode() {
        return opCode;
    }

    public int getErrorCode() {
        return errorCode;
    }

    public byte[] getData() {
        return data;
    }

    public boolean isDone() {
        return done;
    }
    private byte[] byteMerger(byte[] bt1, byte[] bt2){
        byte[] bt3 = new byte[bt1.length+bt2.length];
        System.arraycopy(bt1, 0, bt3, 0, bt1.length);
        System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
        return bt3;
    }
    public void feedValue(byte[] bytes){
        byte[] bt3 = new byte[data.length+bytes.length];
        System.arraycopy(data, 0, bt3, 0, data.length);
        System.arraycopy(bytes, 0, bt3, data.length, bytes.length);
        this.data =bt3;
    }

    public static ResponseData from(int opCode,int errorCode,boolean done){
        return new ResponseData(opCode,errorCode,new byte[]{},done);
    }

    public static ResponseData fromValue(byte[] value) {
        int opCode = HexUtil.byteTwoToIntLittle(value, HEAD.length);
        int errorCode = value[HEAD.length+2+1];
        boolean error = (value[HEAD.length+2] & 0x01) > 0;
//        byte payloadLen = (byte)(0x00ff &value[HEAD.length+2+2]);
        int payloadLen = value[HEAD.length+2+2];
        payloadLen=payloadLen>=0?payloadLen:payloadLen+256;

        int length = value.length;
        boolean done = value[length-1] == TAIL[1] && value[length-2] == TAIL[0];
        byte[] data =Arrays.copyOfRange(value, HEAD.length+2+2+1, HEAD.length+2+2+1+payloadLen);
        return new ResponseData(
                opCode,
                errorCode,
                data,
                done
        );
    }

    @Override
    public String toString() {
        return "ResponseData{" +
                "opCode=" + opCode +
                ", errorCode=" + errorCode +
                ", data=" + Arrays.toString(data) +
                ", done=" + done +
                '}';
    }
}
